<template>
	<view class="fwcontainer">
		<view class="uni-padding-wrap uni-common-mt">
			<form @submit="bindSubmit" @reset="bindReset">
				<view class="uni-form-item uni-column">
					<view class="uni-title euni-label-require">车牌号</view>					
					<view class="uni-input" @click="bindCarsnSelector" v-if="dataInfo.carId != -1">{{dataInfo.carText}}</view>
					<view class="uni-input" @click="bindCarsnSelector" v-else>选择车牌号</view>
				</view>
				<view class="uni-flex uni-column">
					<view class="text euni-flex-left">维护列表</view>
					<view class="uni-flex-item uni-column list-item-container" v-for="(item,index) in dataItems">
						<view class="list-item uni-flex uni-row">
							<view class="text euni-label-property">项目一级</view>
							<view class="uni-flex-item">
								<picker mode="selector" @change="bindItemChange" :data-index="index" data-level="1" :value="item.repair_item_index1" :range="item.repair_items1" range-key="title">
									<view class="uni-input" v-if="item.repair_items1.length > 0 && item.repair_item_index1 != -1">{{item.repair_items1[item.repair_item_index1].title}}</view>
									<view class="uni-input" v-else >选择项目</view>
								</picker>
							</view>
						</view>
						<view class="list-item uni-flex uni-row">
							<view class="text euni-label-property">项目二级</view>
							<view class="uni-flex-item">
								<picker mode="selector" @change="bindItemChange" :data-index="index" data-level="2" :value="item.repair_item_index2" :range="item.repair_items2" range-key="title">
									<view class="uni-input" v-if="item.repair_items2.length > 0 && item.repair_item_index2 != -1">{{item.repair_items2[item.repair_item_index2].title}}</view>
									<view class="uni-input" v-else >选择项目</view>
								</picker>
							</view>
						</view>
						<view class="list-item uni-flex uni-row">
							<view class="text euni-label-property">项目三级</view>
							<view class="uni-flex-item">
								<picker mode="selector" @change="bindItemChange" :data-index="index" data-level="3" :value="item.repair_item_index3" :range="item.repair_items3" range-key="title">
									<view class="uni-input" v-if="item.repair_items3.length > 0 && item.repair_item_index3 != -1">{{item.repair_items3[item.repair_item_index3].title}}</view>
									<view class="uni-input" v-else >选择项目</view>
								</picker>
							</view>
						</view>
						<view class="list-item uni-flex uni-row">
							<view class="text euni-label-property">说明</view>
							<view class="uni-textarea uni-flex-item">
								<textarea v-model:value="item.remark" maxlength="100" placeholder="请输入补充说明"/>
							</view>
							<view class="uni-flex uni-column" style="justify-content: flex-end;">
								<button class="mini-btn" @click="bindItemDel" :data-index="index" type="warn" size="mini" v-if="index > 0">删除</button>
								<button class="mini-btn" @click="bindItemAdd" :data-index="index"  style="margin-top: 20rpx;" type="primary" size="mini" v-if="index >= dataItemsMaxIndex">增加</button>
							</view>
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="uni-title euni-label-require">行驶里程</view>
					<view class="uni-flex uni-row">
						<view class="uni-flex-item euni-flex-autowidth">
							<input class="uni-input" name="mileage" :value="dataInfo.mileage" placeholder="请输入行驶里程" maxlength="9" type="number" />
						</view>
						<view class="text euni-label-tip">km</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="uni-title euni-label-require">消费金额（示例：100.55）</view>
					<view class="uni-flex uni-row">
						<view class="uni-flex-item euni-flex-autowidth">
							<input class="uni-input" name="subtotal" :value="dataInfo.subtotal" placeholder="请输入消费金额" maxlength="8" />
						</view>
						<view class="text euni-label-tip">元</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="uni-title">维护概述</view>
					<view class="uni-textarea">
						<textarea name="remark" :value="dataInfo.remark" maxlength="150" placeholder="请输入维护概述" />
						</view>
				</view>
				<button form-type="submit" type="primary" :disabled="dataSubmitDisabled" :loading="dataSubmitLoading" class="submit-button">保存数据</button>
				<!-- <button form-type="reset">重置</button> -->
			</form>
		</view>
	</view>
</template>

<script>	
	import uniCombox from "@/components/uni-combox/uni-combox";
	var  graceChecker = require('@/static/common/graceChecker.js');
	
	const APP = getApp();
	
	export default {
	    components: {
			uniCombox
		},
		data() {
			return {
				//设置数据
				dataId:-1,
				dataInfo:{carId:-1,carText:'',mileage:'',subtotal:'',remark:''},
				dataItemObj:{id: -1,repair_item_id1:0,repair_items1:[],repair_item_index1:-1,repair_item_id2:0,repair_items2:[],repair_item_index2:-1,repair_item_id3:0,repair_items3:[],repair_item_index3:-1, remark: ''},
				dataItems:[],
				dataItemsMaxIndex:-1,
				//控制组件
				dataSubmitDisabled:false,
				dataSubmitLoading:false,
				//其他标识
				dataRefreshPrepage:false,
			}
		},
		computed:{
			
		},
		methods:{			
			bindReset(e){
				console.log(e);
			},
			bindSubmit(e){
				let _this = this;
				
				//定义表单规则
				var rule = [
				    {name:"car_id", checkType : "notnull", checkRule:"",  errorMsg:"请选择车牌号"},
					{name:"mileage", checkType : "string", checkRule:"1,9",  errorMsg:"请输入1位至9位的行驶里程"},
					// {name:"subtotal", checkType : "reg", checkRule:"(0\.(?!0+$)\d{1,2}|^[1-9][0-9]{0,8}(\.\d{1,2})?)",  errorMsg:"请输入正确消费金额"},
					{name:"subtotal", checkType : "decimal", checkRule:"",  errorMsg:"请输入正确消费金额"}
				];
				//进行表单检查
				var formData = e.detail.value;						
				formData.car_id = (_this.dataInfo.carId == -1)?'':_this.dataInfo.carId;
				var checkRes = graceChecker.check(formData, rule);
				if(checkRes){
					this.doSubmitSwitch(true,true);
					let fields = {
						car_id:formData.car_id,
						mileage:formData.mileage,
						subtotal:formData.subtotal,
						remark:formData.remark,
						'repairItem1':[],
						'repairItem2':[],
						'repairItem3':[],
						'repairRemark':[]
					};
					//组装数组
					let tmpItem = {};
					for(let index in _this.dataItems){
						tmpItem = _this.dataItems[index];
						fields.repairItem1.push(tmpItem.repair_item_id1);
						fields.repairItem2.push(tmpItem.repair_item_id2);
						fields.repairItem3.push(tmpItem.repair_item_id3);
						fields.repairRemark.push(tmpItem.remark);
					}
					
					if(_this.dataId !== -1) fields.id = _this.dataId;
					
					APP._post('/api/record/form',fields, null, function (res) {
					  //执行成功
					  if (res.code === APP.appconfig.fwcode.successed) {
						APP.apptool.showToastInfo(res.msg, null, 2000, function (res) {
							 APP.apptool.navigateBackPage(1, function (targetPage) {
								if (_this.dataRefreshPrepage) {
								  //需刷新数据面，必须实现refreshPage()方法
								  targetPage.refreshPage();
								}
							 });
						});
					  } else {
						APP.apptool.showToastInfo(res.msg);
					  }
					}, function (res) {
					  //执行失败
					}, function (res) {
					  //执行完成
					  _this.doSubmitSwitch(false,false);
					});
				}else{
				    uni.showToast({ title: graceChecker.error, icon: "none" });
				}
			},
			bindCarsnSelector(e){
				wx.navigateTo({
					url:'/pages/home/sub/record-search'
				});
			},
			bindItemChange(e){
				let dataset = e.currentTarget.dataset;
				let value = e.detail.value;
				let currentItem = this.dataItems[dataset.index];
				let level = parseInt(dataset.level);
				let itemId = -1;
				
				if(level == 1){
					if(currentItem.repair_items1.length > value){
						currentItem.repair_item_index1 = value;
						itemId = currentItem.repair_item_id1 = currentItem.repair_items1[value].id;	
					}					
				}else if(level == 2){
					if(currentItem.repair_items2.length > value){
						currentItem.repair_item_index2 = value;
						itemId = currentItem.repair_item_id2 = currentItem.repair_items2[value].id;
					}
				}else if(level == 3){
					if(currentItem.repair_items3.length > value){
						currentItem.repair_item_index3 = value;
						itemId = currentItem.repair_item_id3 = currentItem.repair_items3[value].id;
					}
				}				
				if(-1 !== itemId){
					this.loadRepairItem(itemId,(level+1),dataset.index,function(){
						if(level == 1){
							currentItem.repair_item_index2 = -1;
							currentItem.repair_item_index3 = -1;
						}else if(level == 2){
							currentItem.repair_item_index3 = -1;
						}						
					});			
				}				
			},
			bindItemAdd(e) {				
				this.dataItems.push(this.cloneRefer(this.dataItemObj));
				this.synItemLastIndex();
			},
			bindItemDel(e) {
				let dataset = e.currentTarget.dataset;
				let _this = this;
				APP.apptool.showModalConfirm('提示', '确认删除该项？', '取消', '删除', function(confirm, cancel){
					if(cancel) return;
					
					_this.dataItems.splice(dataset.index, 1);
					_this.synItemLastIndex();
				});
			},
			synItemLastIndex:function(){
				//初始化数据
				this.dataItemsMaxIndex = this.dataItems.length - 1;
			},
			getItems: function () {
				return JSON.stringify(this.items);
			},
			cloneRefer:function(obj){
				return JSON.parse(JSON.stringify(obj));
			},
			loadRepairItem:function(pid,level,index,completedcallback){
				let _this = this;
				APP._post('/api/record/repair_items', {
					pid: pid
				}, null, function(res) {
					//执行成功
					if (res.code === APP.appconfig.fwcode.successed) {
						let data = res.data;
						if(-1 == index){
							if(level == 1){
								_this.dataItemObj.repair_items1 = data;	
							}else if(level == 2){
								_this.dataItemObj.repair_items2 = data;
							}else if(level == 3){
								_this.dataItemObj.repair_items3 = data;
							}
						}else{
							if(level == 1){
								_this.dataItems[index].repair_items1 = data;	
							}else if(level == 2){
								_this.dataItems[index].repair_items2 = data;
							}else if(level == 3){
								_this.dataItems[index].repair_items3 = data;
							}
						}
					} else {
						APP.apptool.showToastInfo(res.msg);
					}
				}, function(res) {
					//执行失败
				}, function(res) {
					//执行完成					
					completedcallback && completedcallback();
				});
			},
			loadPageData: function(completedcallback) {
				let _this = this;
				APP._post('/api/record/info', {
					tid: _this.dataId
				}, null, function(res) {
					//执行成功
					if (res.code === APP.appconfig.fwcode.successed) {
						let data = res.data,listItem = {}, tmpList = [];
						_this.dataInfo = {carId:data.info.car_id, carText:data.info.car_sn,mileage:data.info.mileage,subtotal:data.info.subtotal,remark:data.info.remark};					
						for (let index in data.detaillist) {
							listItem = data.detaillist[index];
							// listItem.repair_items1 = JSON.parse(listItem.repair_items1);
							if(listItem.repair_items1.length > 0){
								for(let idx1 in listItem.repair_items1){
									if(parseInt(listItem.repair_items1[idx1].id) == parseInt(listItem.repair_item_id1)){									
										listItem.repair_item_index1 = parseInt(idx1);
										break;
									}
								}
							}else{
								listItem.repair_item_index1 = -1;
							}
							
							// listItem.repair_items2 = JSON.parse(listItem.repair_items2);
							if(listItem.repair_items2.length > 0){
								for(let idx2 in listItem.repair_items2){
									if(parseInt(listItem.repair_items2[idx2].id) == parseInt(listItem.repair_item_id2)){
										listItem.repair_item_index2 = parseInt(idx2);
										break;
									}
								}
							}else{
								listItem.repair_item_index2 = -1;
							}
							
							// listItem.repair_items3 = JSON.parse(listItem.repair_items3);
							if(listItem.repair_items3.length > 0){
								for(let idx3 in listItem.repair_items3){
									if(parseInt(listItem.repair_items3[idx3].id) == parseInt(listItem.repair_item_id3)){
										listItem.repair_item_index3 = parseInt(idx3);
										break;
									}
								}
							}else{
								listItem.repair_item_index3 = -1;
							}
							tmpList = tmpList.concat(listItem);
						}						
						//同步最大索引
						_this.dataItemsMaxIndex = tmpList.length - 1;
						//设置数据
						_this.dataItems = tmpList;
					} else {
						APP.apptool.showToastInfo(res.msg);
					}
				}, function(res) {
					//执行失败
				}, function(res) {
					//执行完成
					completedcallback && completedcallback();
				});
			},
			doSubmitSwitch: function(disabled, loading){
				this.dataSubmitDisabled = disabled;
				this.dataSubmitLoading = loading;
			}
		},
		onLoad(options) {
			let _this = this;
			if (options.refreshpage){
				//刷新标识：refreshpage=refresh
				this.dataRefreshPrepage = (options.refreshpage=='refresh');
			}
			if (options.tid){
				_this.dataId = options.tid;
				_this.loadPageData(function(){
					_this.loadRepairItem(0,1,-1,function(){
						// _this.dataItems = _this.dataItems.concat(_this.dataItemObj);					
						if(_this.dataItems.length < 1){
							_this.dataItems.push(_this.dataItemObj);	
						}						
					});
				});
			}else{
				//初始化数据
				_this.loadRepairItem(0,1,-1,function(){
					// _this.dataItems = _this.dataItems.concat(_this.dataItemObj);					
					_this.dataItems.push(_this.dataItemObj);
				});
			}			
		},
		onShow() {
			this.synItemLastIndex();
		}
	}
</script>

<style>
	.submit-button{margin-top: 20px;}
	.list-item-container{
		background-color: #FFFFFF;
		padding: 10rpx;
		border: 1rpx dotted #888888;
		margin-bottom: 10rpx;
	}
</style>
